﻿using Basic.FlowApplication.Interface;
using Basic.FlowApplication.Model;
using Basic.FlowApplication.Model.AppMsg;
using Basic.FlowCollect;
using Basic.FlowModel.DB;
using WeDonekRpc.CacheClient.Interface;

namespace Basic.FlowApplication.lmpl
{
    internal class FlowAppService : IFlowAppService
    {
        private readonly IFlowAppCollect _App;
        private readonly IFlowAppMsgTemplateCollect _AppMsg;
        private readonly ILocalCacheController _LocalCache;

        public FlowAppService ( IFlowAppCollect app,
            IFlowAppMsgTemplateCollect appMsg,
            ILocalCacheController localCache )
        {
            this._App = app;
            this._AppMsg = appMsg;
            this._LocalCache = localCache;
        }
        public FlowAppBody Get ( long appId )
        {
            string key = "FlowApp_" + appId;
            if ( !this._LocalCache.TryGet(key, out FlowAppBody app) )
            {
                app = this._Get(appId);
                _ = this._LocalCache.Set(key, app, DateTime.Now.AddHours(12));
            }
            return app;
        }

        public string GetAppName ( long appId )
        {
            return this._App.GetAppName(appId);
        }

        private FlowAppBody _Get ( long appId )
        {
            DBFlowApp body = this._App.Get(appId);
            FlowAppBody app = new FlowAppBody
            {
                AppName = body.AppName,
                AppClassify = body.AppClassify,
                Status = body.Status,
                AppType = body.AppType,
                FlowId = body.FlowId,
                Id = body.Id,
                FlowVer = body.FlowVer,
                TitleTemplate = body.TitleTemplate
            };
            app.Template = this._AppMsg.Gets<FlowAppMsgTemplate>(appId);
            return app;
        }
    }
}
